<template>
  <div v-if="fileData || sheetList" style="overflow: hidden">
    <div class="btn-group">
      <px-button v-has="'REPORT_PREVIEW_PRINT'" @click="printFile">打印</px-button>
      <px-button v-has="'REPORT_PREVIEW_DOWNLOAD'" type="primary" @click="downloadFile">下载</px-button>
    </div>

    <div id="print-content" class="preview-container">
      <div v-if="['xlsx'].includes(route.query.fileType)">
        <div v-for="(item, index) in sheetList" v-show="item.isSelected" :key="index" class="excelTable" v-html="item.content" />
      </div>
      <div v-else-if="['pdf'].includes(route.query.fileType)" class="pdf-viewer" style="height: 100%">
        <iframe :src="fileData" width="100%" height="100%" frameborder="0" />
      </div>

      <!-- <vue-office-excel v-if="['xlsx'].includes(route.query.fileType)" :src="fileData" />

      <vue-office-docx v-if="['docx'].includes(route.query.fileType)" :src="fileData" />

      <vue-office-pdf v-if="['pdf'].includes(route.query.fileType)" :src="fileData" /> -->
      <img v-else-if="['jpeg', 'png', 'jpg', 'gif', 'bmp', 'tif'].includes(route.query.fileType)" :src="fileData" style="width: 100%" />
      <!-- <div v-else-if="['txt'].includes(route.query.fileType)" class="txt" style="white-space: pre-wrap">
        {{ fileData }}
      </div> -->
      <div v-else class="tips">暂不支持预览！请直接下载</div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { onMounted, reactive, toRefs, ref, computed, getCurrentInstance } from "vue";
// import VueOfficeDocx from "@vue-office/docx";
// import VueOfficeExcel from "@vue-office/excel";
import * as XLSX from "xlsx/xlsx.mjs";
// import VueOfficePdf from "@vue-office/pdf";
import "@vue-office/docx/lib/index.css";
import printJS from "print-js";
import axios from "axios";
import { getToken } from "@/utils/auth";
import { useRoute, useRouter } from "vue-router";

const route = useRoute();

const fileData = ref();
const sheetList = ref([]);
const pdfCanvas = ref();
const printFile = () => {
  printJS({
    printable: "print-content",
    type: "html",
    style: `@page {size: auto;margin: 0;}
          .peintdiv{
              height:207mm
          }
          `, // 去掉页眉页脚
    scanStyles: false,
    // targetStyles: ['*'],
    header: null,
    documentTitle: ""
  });
};
const { proxy }: any = getCurrentInstance();

const previewFile = () => {
  const params = {
    id: route.query.id, //1343
    fileName: route.query.fileName, //'202406271346221806202393046802432.xlsx' ,
    moduleName: route.query.moduleName || ""
  };
  axios({
    method: "post",
    url: "/ifp/sharing/api/v1/file/download",
    headers: {
      "Content-Type": "application/json",
      Authorization: "Bearer " + getToken().accessToken || "",
      facCode: localStorage.getItem("facCode") || ""
    },
    data: params,
    responseType: "arraybuffer"
  }).then(res => {
    if (["jpeg", "png", "jpg", "gif", "bmp", "tif", "txt"].includes(route.query.fileType)) {
      fileData.value = URL.createObjectURL(new Blob([res.data]));
    } else {
      if (["xlsx"].includes(route.query.fileType)) {
        let workbook = XLSX.read(res.data, { type: "binary" });
        let sheetFileList = workbook.SheetNames;

        sheetFileList.forEach((item, index) => {
          let ws = workbook.Sheets[item];
          let fileContent = "";
          try {
            // 把excel文件流转化为html字符串，以便于v-html使用
            fileContent = XLSX.utils.sheet_to_html(ws);
          } catch (error) {}
          sheetList.value.push({
            name: item,
            isSelected: index == 0,
            content: fileContent
          });
        });
      } else if (["pdf"].includes(route.query.fileType)) {
        fileData.value = URL.createObjectURL(new Blob([res.data], { type: "application/pdf;chartset=utf-8" }));
      } else {
        fileData.value = new Blob([res.data]); //,{type:'application/pdf;chartset=utf-8'})   ,{ type: 'text/xlsx;charset=utf-8' }
      }

      //fileData.value = new Blob([res.data]); //,{type:'application/pdf;chartset=utf-8'})   ,{ type: 'text/xlsx;charset=utf-8' }
    }
  });
};

const downloadFile = () => {
  const params = {
    id: route.query.id, //1343
    fileName: route.query.fileName, //'202406271346221806202393046802432.xlsx' ,
    moduleName: route.query.moduleName || ""
  };
  proxy.download("post", "/sharing/api/v1/file/download", params, "202406271447311806217782057230336.jpg");
};
onMounted(() => {
  previewFile();
});
</script>
<style scoped lang="scss">
.btn-group {
  margin: 10px;
  text-align: center;
}

.preview-container {
  height: calc(100vh - 58px);
  overflow-y: auto;
}

.tips {
  padding-top: 20px;
  text-align: center;
}

:deep(.excelTable) {
  table {
    border-collapse: collapse !important;
    background-color: #fff;

    td {
      padding: 12px;
      font-size: 14px;
      color: #666;
      word-break: keep-all;
      white-space: nowrap;
      border: 1px solid #000;
    }
  }
}
</style>
